﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using Hi_Baidu.Packet;
using System.Net;
using NetMeeting_Server.Config;
using Hi_Baidu.Enum.User;

namespace Hi_Baidu.ProcessModel
{
    class LoginProcessModel : Model
    {
        /// <summary>
        ///    当前是否正在登陆的标志位
        /// </summary>
        public static LOGIN LOGINSTATE = LOGIN.LOGIN_AGO;

        /// <summary>
        ///    登陆枚举标志位
        /// </summary>
        public enum LOGIN : int
        {
            /// <summary>
            ///    还没登陆
            /// </summary>
            LOGIN_AGO,
            /// <summary>
            ///    登陆中
            /// </summary>
            LOGINNING,
            /// <summary>
            ///    登陆成功后
            /// </summary>
            LOGINED
        }

        private static System.Timers.Timer timer_Notify;
        private static int ICON_INDEX = 445;

        /// <summary>
        ///     通过用户名和密码解析出登陆协议字符串
        /// </summary>
        /// <param name="username" type="string">
        ///     <para>
        ///         登录名
        ///     </para>
        /// </param>
        /// <param name="password" type="string">
        ///     <para>
        ///         密码
        ///     </para>
        /// </param>
        /// <returns>
        ///     返回解析后的登陆协议字符串
        /// </returns>
        public static byte[] LoginParser(byte[] username, byte[] password, byte[] LoginState)
        {
            if (username.Length > 0 && password.Length > 0)
            {
                byte[] UsernameLength = BitConverter.GetBytes(username.Length);
                byte[] PasswordLength = BitConverter.GetBytes(password.Length);
                byte[] IPAddress = Encoding.Default.GetBytes(Dns.GetHostAddresses(Dns.GetHostName())[0].ToString());
                byte[] IPLength = BitConverter.GetBytes(IPAddress.Length);
                byte[] TalkPort = BitConverter.GetBytes(Globle.user.TALK_PORT);
                byte[] VideoPort = BitConverter.GetBytes(Globle.user.VIDEO_PORT);
                byte[] VoicePort = BitConverter.GetBytes(Globle.user.VOICE_PORT);
                byte[] TransferFilePort = BitConverter.GetBytes(Globle.user.TRANSFER_FILE_PORT);
                byte[] None = new byte[2];
                byte[] PackageBody = new byte[username.Length + password.Length +  LoginState.Length + None.Length + IPAddress.Length + 34];
                Offset = 0;
                //用户名长度
                Array.ConstrainedCopy(UsernameLength, 0, PackageBody, Offset, UsernameLength.Length);
                Offset += 4;
                //用户名
                Array.ConstrainedCopy(username, 0, PackageBody, Offset, username.Length);
                Offset += username.Length;
                //密码长度
                Array.ConstrainedCopy(PasswordLength, 0, PackageBody, Offset, PasswordLength.Length);
                Offset += 4;
                //密码
                Array.ConstrainedCopy(password, 0, PackageBody, Offset, password.Length);
                Offset += password.Length;
                //登录状态
                Array.ConstrainedCopy(LoginState, 0, PackageBody, Offset, LoginState.Length);
                Offset += 4;
                //空白 
                Array.ConstrainedCopy(None, 0, PackageBody, Offset, None.Length);
                Offset += 2;
                //IP地址长度
                Array.ConstrainedCopy(IPLength, 0, PackageBody, Offset, IPLength.Length);
                Offset += 4;
                //IP地址
                Array.ConstrainedCopy(IPAddress, 0, PackageBody, Offset, IPAddress.Length);
                Offset += IPAddress.Length;
                //聊天端口
                Array.ConstrainedCopy(TalkPort, 0, PackageBody, Offset, TalkPort.Length);
                Offset += 4;
                //视频端口
                Array.ConstrainedCopy(VideoPort, 0, PackageBody, Offset, VideoPort.Length);
                Offset += 4;
                //音频端口
                Array.ConstrainedCopy(VoicePort, 0, PackageBody, Offset, VoicePort.Length);
                Offset += 4;
                //文件传送端口
                Array.ConstrainedCopy(TransferFilePort, 0, PackageBody, Offset, TransferFilePort.Length);

                return ProtocolFactory.ProtocolFactory.GetProtocol("Login",
                                                                   (int) Protocol.OUT_NetworkCommand.LOGIN_PACKAGE,
                                                                   (int) Protocol.NetworkProtocol.Base,
                                                                   PackageBody, ProtocolFactory.ProtocolFactory.ACK.Yes,
                                                                   ProtocolFactory.ProtocolFactory.ENCRYPT.No,
                                                                   Globle.user.SESSION_CODE);
            }
            return null;
        }

        /// <summary>
        ///     将指定用户登录到服务器
        /// </summary>
        /// <param name="username" type="string">
        ///     <para>
        ///         登录名
        ///     </para>
        /// </param>
        /// <param name="password" type="string">
        ///     <para>
        ///         密码
        ///     </para>
        /// </param>
        public static void Login(byte[] Package)
        {
            if (Package != null)
            {
                NetControl.Send(Package, 8700, "localhost");
            }
        }

        /// <summary>
        ///     取消登录
        /// </summary>
        /// <param name="WinLogin" type="Hi_Baidu.Window1">
        ///     <para>
        ///         登陆主窗体
        ///     </para>
        /// </param>
        public static void CancleLogin(Window1 WinLogin)
        {
            //取消挂载超时器
            Globle.timeoutTimerManager.RemoveTimer("LoginTimerOut");
            LoginProcessModel.ChangeState(false, WinLogin);
        }

        /// <summary>
        ///    退出当前软件
        ///    并且释放在任务栏的图标
        /// </summary>
        public static void Logout()
        {
            Globle.user.NI.Visible = false;
            Globle.user.NI.Dispose();
        }

        /// <summary>
        ///     更改当前登录状态
        /// </summary>
        /// <param name="Loginning" type="bool">
        ///     <para>
        ///         登录状态 (登陆 - True / 取消 - False)
        ///     </para>
        /// </param>
        /// <param name="WinLogin" type="Hi_Baidu.Window1">
        ///     <para>
        ///         登录窗体
        ///     </para>
        /// </param>
        public static void ChangeState(bool Loginning, Window1 WinLogin)
        {
            //正在登陆
            if (Loginning)
            {
                LOGINSTATE = LOGIN.LOGINNING;
                Globle.user.USER_ONLINE_STATE = ONLIN_STATE.LOGINNING;
                NOFIFY_LOGINNING_ICON();
                //LoginProcessModel.TOOLTIP_NOTIFY_ICON();
                WinLogin.btn_Login.Content = "取消";
                WinLogin.cmb_Username.IsEnabled = false;
                WinLogin.password1.IsEnabled = false;
                WinLogin.ckb_RememberPassword.Visibility = Visibility.Hidden;
                WinLogin.ckb_AutoLogin.Visibility = Visibility.Hidden;
                WinLogin.imageExpender1.Visibility = Visibility.Visible;
                ShowLoginNotifyImage(WinLogin);
            }
            //登录失败
            else
            {
                LOGINSTATE = LOGIN.LOGIN_AGO;
                Globle.user.USER_ONLINE_STATE = ONLIN_STATE.OFFLINE;
                //LoginProcessModel.TOOLTIP_NOTIFY_ICON();
                WinLogin.btn_Login.Content = "登陆";
                WinLogin.cmb_Username.IsEnabled = true;
                WinLogin.password1.IsEnabled = true;
                WinLogin.ckb_RememberPassword.Visibility = Visibility.Visible;
                WinLogin.ckb_AutoLogin.Visibility = Visibility.Visible;
                WinLogin.imageExpender1.Visibility = Visibility.Hidden;
            }
        }

        public static void ShowLoginNotifyImage(Window1 WinLogin)
        {
            Stream imageStream = Application.GetResourceStream(new Uri(@"SysImage/7589a26e0048d6ca81cb4a9d.gif", UriKind.Relative)).Stream;
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(imageStream);
            WinLogin.imageExpender1.Image = bitmap;
        }

        /// <summary>
        ///    正在登录方法，该方法激活后
        ///    将会产生任务栏图标动画效果
        /// </summary>
        public static void NOFIFY_LOGINNING_ICON()
        {
            timer_Notify = new System.Timers.Timer(100);
            timer_Notify.Elapsed += new System.Timers.ElapsedEventHandler(timer_Notify_Elapsed);
            timer_Notify.Start();
        }

        /// <summary>
        ///    根据登录状态在任务栏图标显示提示信息
        /// </summary>
        public static void TOOLTIP_NOTIFY_ICON()
        {
            switch (LOGINSTATE)
            {
                case LOGIN.LOGIN_AGO:
                    Globle.user.NI.Text = "Baidu HI - IM - 当前未登录";
                    break;
                case LOGIN.LOGINED:
                    Globle.user.NI.Text = "Baidu HI - IM\r\n欢迎回来, 用户：" +
                                                   Encoding.Default.GetString(Globle.user.DIC_USERINFO["NICKNAME"]);
                    break;
            }
        }

        static void timer_Notify_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Icon IC = null;
            if (LOGINSTATE == LOGIN.LOGINNING)
            {
                IC = new Icon(@"../Icon/ICON_LL/" + ICON_INDEX + ".ico", new System.Drawing.Size(16, 16));
                Globle.user.NI.Icon = IC;

                if (ICON_INDEX < 462)
                {
                    ICON_INDEX++;
                }
                else
                {
                    timer_Notify.Stop();
                    timer_Notify.Dispose();
                    ICON_INDEX = 445;
                    NOFIFY_LOGINNING_ICON();
                }
            }
            else if (LOGINSTATE == LOGIN.LOGIN_AGO)
            {
                timer_Notify.Stop();
                timer_Notify.Dispose();
                ICON_INDEX = 445;
                cls_Application_Init.SetNoityIconByUserState(ONLIN_STATE.OFFLINE);
                Globle.user.NI.Visible = true;
                return;
            }
            else
            {
                timer_Notify.Stop();
                timer_Notify.Dispose();
                ICON_INDEX = 445;
                cls_Application_Init.SetNoityIconByUserState(Globle.user.USER_ONLINE_STATE);
                Globle.user.NI.Visible = true;
                return;
            }
        }
    }
}
